﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Ditto.Models
{
    //Refactor this so "Save" functions are in "Repository" class. Use System.Drawing.Image here as method, property or inherit
    public class Image
    {
        public Image(HttpPostedFileBase file)
        {
            //Path = path;
            File = file;
        }
        //public string Path { get; set; }
        public HttpPostedFileBase File { get; set; }

        public void Save(string path) 
        {
            this.File.SaveAs(path);
        }

        public void SaveThumbnail_LQ(string path)
        {
            System.Drawing.Image fullImage = System.Drawing.Image.FromStream(this.File.InputStream, true, true);

            int newWidth = 235;
            int newHeight = (int)(((double)fullImage.Height / (double)fullImage.Width) * newWidth);

            using (System.Drawing.Image thumbPhoto =
                fullImage.GetThumbnailImage(newWidth, newHeight, null, new System.IntPtr()))
            {
                using (System.IO.FileStream ms = new System.IO.FileStream(path, System.IO.FileMode.Create))
                {
                    thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

        public void SaveThumbnail(string path)
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(this.File.InputStream, true, true);
            int newWidth = 235;
            int newHeight = (int)(((double)image.Height / (double)image.Width) * newWidth);

            var thumbnailBitmap = new System.Drawing.Bitmap(newWidth, newHeight);

            var thumbnailGraph = System.Drawing.Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            var imageRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
            thumbnailGraph.DrawImage(image, imageRectangle);

            using (System.IO.FileStream ms = new System.IO.FileStream(path, System.IO.FileMode.Create))
            {
                thumbnailBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
            image.Dispose();
        }

    }
}